<?php
// @formatter:off
/**
 * @file ct.lists.update.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-08-20 00:23:06 +0000 (Tue, 20 Aug 2013) $
 *
 * $Id: ct.lists.update.php 102 2013-08-20 00:23:06Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/branches/wcomix-1.0/cron/ct.lists.update.php $
 */
// @formatter:on

class WCComicsUpdateList extends WCCronTool {
	public function run($spacer = "") {
		//
		// Loading global pointers.
		global $wcDefaults;
		global $wcTagsHolder;
		global $wcSpecialTags;
		global $wcPatterns;
		global $wcGroupsHolder;
		global $wcDirectoriesHolder;
		//
		// Checking that Read Only Mode is not activated.
		if(!$wcDefaults["read-only"]) {
			$dbCode = md5(__FILE__);
			$dirExceptions = array(
				".",
				".."
			);

			$query = "update  {$this->_dbprefix}comics\n";
			$query .= "set     cmc_checked = :checked,\n";
			$query .= "        cmc_lost    = 'Y'\n";
			$query .= "where   cmc_group     = :group\n";
			$query .= " and    cmc_directory = :directory\n";
			$stmtChecks = $this->_db->prepare("{$dbCode}[1]", $query);

			$query = "insert\n";
			$query .= "        into {$this->_dbprefix}comics (\n";
			$query .= "                cmc_group, cmc_directory, cmc_name, cmc_size)\n";
			$query .= "        values (:group, :directory, :comic, :size)\n";
			$query .= "        on duplicate key\n";
			$query .= "                update  cmc_checked = 'Y',\n";
			$query .= "                        cmc_lost    = 'N',\n";
			$query .= "                        cmc_size    = :size\n";
			$stmtAddComic = $this->_db->prepare("{$dbCode}[2]", $query);

			$query = "insert\n";
			$query .= "        into {$this->_dbprefix}directories (\n";
			$query .= "                dir_group, dir_name, dir_next_name)\n";
			$query .= "        values (:group, :name, '')\n";
			$stmtAddDirectory = $this->_db->prepare("{$dbCode}[3]", $query);

			$query = "update  {$this->_dbprefix}directories\n";
			$query .= "set     dir_count  = :entries,\n";
			$query .= "        dir_dcount = :dentries\n";
			$query .= "where   dir_group = :group\n";
			$query .= " and    dir_id    = :directory\n";
			$stmtStats = $this->_db->prepare("{$dbCode}[4]", $query);

			$query = "update  {$this->_dbprefix}comics\n";
			$query .= "set     cmc_lost    = 'Y'\n";
			$query .= "where   cmc_checked = 'N'\n";
			$query .= " and    cmc_lost    = 'N'\n";
			$query .= " and    dir_group = :group\n";
			$query .= " and    dir_id    = :directory\n";
			$stmtLosts = $this->_db->prepare("{$dbCode}[5]", $query);

			// Checking every group.
			foreach($wcGroupsHolder->groups() as $group) {
				if(is_readable($group->root)) {
					echo "{$spacer}Checking group '{$group->name}' ({$group->id}):\n";

					$wcTagsHolder->createSpecialTags();
					$groupChanged = false;
					//
					// Checking every directory.
					foreach($group->directoriesFull() as $directory) {
						$fullPath = WCSanitizer::SystemPath($directory->fullPath());
						if($directory->ok() & $directory->isChanged()) {
							echo "{$spacer}\tChecking directory '{$directory->name}': ";
							//
							// Directory stats are
							// changed, therefore
							// groups count must be
							// updated.
							$groupChanged = true;

							$stmtChecks->execute(array(
								":checked" => $directory->ok() ? "N" : "Y",
								":group" => $group->id,
								":directory" => $directory->id
							));

							if($directory->ok()) {
								$d = scandir($fullPath);
								$comics = array();
								$directories = array();
								//
								// Checking every
								// file.
								foreach($d as $entry) {
									// Checking every pattern.
									foreach($wcPatterns["comic-patterns"] as $pattern) {
										if(preg_match($pattern, $entry)) {
											$comics[] = $entry;
										} elseif(is_dir($fullPath.DIRECTORY_SEPARATOR.$entry)) {
											$tip = substr($entry, 0, 1);
											if(!in_array($entry, $dirExceptions) && ($tip != "." || $wcDefaults["allow-hiddens"])) {
												$directories[] = $entry;
											}
										}
									}
								}
								$directories = array_unique($directories);

								foreach($comics as $comic) {
									$st = stat("{$fullPath}/{$comic}");

									$stmtAddComic->execute(array(
										":group" => $group->id,
										":directory" => $directory->id,
										":comic" => $comic,
										":size" => $st["size"]
									));
								}
								//
								// Checking and adding directories.
								foreach($directories as $dir) {
									$name = "{$directory->name}/{$dir}";
									$name = str_replace("//", "/", $name);
									if(!$wcDirectoriesHolder->itemByName($name, $group)) {
										$stmtAddDirectory->execute(array(
											":group" => $group->id,
											":name" => $name
										));
									}
								}

								$entries = count($comics);
								$dentries = count($directories);
								echo "{$entries} comics. {$dentries} directories.";
								//
								// Updating stats.
								$stmtStats->execute(array(
									":group" => $group->id,
									":directory" => $directory->id,
									":entries" => $entries,
									":dentries" => $dentries
								));
								//
								// Updating losts.
								$stmtLosts->execute(array(
									":group" => $group->id(),
									":directory" => $directory->id
								));

								$directory->updateTimes();
							} else {
								echo WCColorText::ShellRed("directory seems to be broken");
							}

							echo "\n";
						}
					}
					//
					// Updating group's count.
					if($groupChanged) {
						$group->count = 0;
						echo "{$spacer}\tGroup's directories: {$group->count()}\n";
					}
				}
			}
		} else {
			echo "{$spacer}".WCColorText::ShellYellow("ReadOnlyMode activated.\n");
		}
	}
	public function showHelp($spacer = "") {
		echo "{$spacer}This tool seeks for any comic in all configured directory and updates the database.\n";
		echo "{$spacer}If this tool is not used periodically, new comics won't be shown and olds may bring problems when broken.\n\n";
		echo "{$spacer}It requires no extra parameters.\n";
	}
	protected function loadOptions() {
		$this->_optionsLoaded = true;
	}
}
?>